﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenTK.Graphics.OpenGL;
using System.Drawing;
using System.Drawing.Imaging;

namespace TestGraphics
{
    public class TextureCache
    {
        // Singleton
        private static TextureCache _instance = new TextureCache();

        public static TextureCache Instance { get { return _instance; } }
        
        // Class
        private IDictionary<string, int> _textures;

        private TextureCache() 
        {
            _textures = new Dictionary<string, int>();
        }

        public void SetCurrentTexture(string name)
        {
            if (!_textures.ContainsKey(name))
                throw new ArgumentException("Doesn't contains " + name);

            GL.BindTexture(TextureTarget.Texture2D, _textures[name]);
        }
        public void LoadTexture(string filename, string targetName)
        {
            if (String.IsNullOrEmpty(filename))
                throw new ArgumentException(filename);

            if (_textures.ContainsKey(targetName))
                throw new ArgumentException("Already contains " + targetName);

            int id = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2D, id);

            Bitmap bmp = new Bitmap(filename);
            BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp_data.Width, bmp_data.Height, 0,
                OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0);

            bmp.UnlockBits(bmp_data);

            // We haven't uploaded mipmaps, so disable mipmapping (otherwise the texture will not appear).
            // On newer video cards, we can use GL.GenerateMipmaps() or GL.Ext.GenerateMipmaps() to create
            // mipmaps automatically. In that case, use TextureMinFilter.LinearMipmapLinear to enable them.
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

            _textures.Add(targetName, id);
        }
    }
}
